import * as THREE from 'three';
import { FrameLoader } from '../core/FrameLoader.js';

export class BaseScene {
    constructor(app, index) {
        this.app = app;
        this.index = index;
        this.name = 'BaseScene';
        this.group = new THREE.Group();
        this.isVisible = true;
        this.isActive = false;
        this.objects = [];
        this.animations = [];
        
        // 性能相关
        this.lodObjects = [];
        this.cullableObjects = [];
        
        // 分帧加载管理器
        this.frameLoader = new FrameLoader();
        this.frameLoader.setProgressCallback(this.onFrameLoadProgress.bind(this));
        this.frameLoader.setCompleteCallback(this.onFrameLoadComplete.bind(this));
        
        // 场景特定的相机位置和目标
        this.cameraPosition = new THREE.Vector3(0, 0, 5);
        this.cameraTarget = new THREE.Vector3(0, 0, 0);
        
        // 环境设置
        this.ambientLightColor = 0x404040;
        this.ambientLightIntensity = 0.4;
        this.directionalLightColor = 0xffffff;
        this.directionalLightIntensity = 1.0;
        
        this.setupLights();
    }
    
    async init() {
        // 子类实现具体的初始化逻辑
        console.log(`${this.name} 初始化开始`);
        await this.createObjects();
        console.log(`${this.name} 初始化完成`);
    }
    
    async createObjects() {
        // 子类实现具体的对象创建逻辑
    }
    
    setupLights() {
        // 环境光
        this.ambientLight = new THREE.AmbientLight(
            this.ambientLightColor, 
            this.ambientLightIntensity
        );
        this.group.add(this.ambientLight);
        
        // 方向光
        this.directionalLight = new THREE.DirectionalLight(
            this.directionalLightColor, 
            this.directionalLightIntensity
        );
        this.directionalLight.position.set(5, 5, 5);
        this.directionalLight.castShadow = true;
        
        // 优化阴影设置
        this.directionalLight.shadow.mapSize.setScalar(1024);
        this.directionalLight.shadow.camera.near = 0.1;
        this.directionalLight.shadow.camera.far = 50;
        this.directionalLight.shadow.camera.left = -10;
        this.directionalLight.shadow.camera.right = 10;
        this.directionalLight.shadow.camera.top = 10;
        this.directionalLight.shadow.camera.bottom = -10;
        
        this.group.add(this.directionalLight);
    }
    
    activate() {
        this.isActive = true;
        
        // 激活场景动画
        this.startAnimations();
        
        // 平滑移动相机到场景位置
        this.animateCamera();
        
        console.log(`${this.name} 已激活`);
    }
    
    deactivate() {
        this.isActive = false;
        
        // 停止场景动画
        this.stopAnimations();
        
        console.log(`${this.name} 已停用`);
    }
    
    prepare() {
        // 场景切换前的准备工作
        this.updateObjects();
    }
    
    setVisible(visible) {
        this.isVisible = visible;
        this.group.visible = visible;
        
        // 优化：隐藏时停止不必要的计算
        if (!visible) {
            this.stopAnimations();
        } else if (this.isActive) {
            this.startAnimations();
        }
    }
    
    update() {
        if (!this.isActive || !this.isVisible) return;
        
        // 更新场景对象
        this.updateObjects();
        
        // 更新动画
        this.updateAnimations();
    }
    
    updateObjects() {
        // 更新分帧加载器
        if (this.frameLoader) {
            this.frameLoader.update(this.addObjectImmediate.bind(this));
        }
        
        // 子类实现具体的对象更新逻辑
    }
    
    updateAnimations() {
        const time = performance.now() * 0.001;
        
        this.animations.forEach(animation => {
            if (animation.update) {
                animation.update(time);
            }
        });
    }
    
    startAnimations() {
        this.animations.forEach(animation => {
            if (animation.start) {
                animation.start();
            }
        });
    }
    
    stopAnimations() {
        this.animations.forEach(animation => {
            if (animation.stop) {
                animation.stop();
            }
        });
    }
    
    animateCamera() {
        const camera = this.app.getCamera();
        const controls = this.app.getControls();
        
        if (controls && controls.target) {
            // 使用GSAP动画平滑移动相机
            import('gsap').then(({ gsap }) => {
                gsap.to(camera.position, {
                    duration: 1.5,
                    x: this.cameraPosition.x,
                    y: this.cameraPosition.y,
                    z: this.cameraPosition.z,
                    ease: "power2.inOut",
                    onUpdate: () => {
                        controls.update();
                    }
                });
                
                gsap.to(controls.target, {
                    duration: 1.5,
                    x: this.cameraTarget.x,
                    y: this.cameraTarget.y,
                    z: this.cameraTarget.z,
                    ease: "power2.inOut",
                    onUpdate: () => {
                        controls.update();
                    }
                });
            });
        }
    }
    
    // 性能优化方法
    adjustQuality(qualitySettings) {
        // 调整粒子数量
        if (qualitySettings.particleCount !== undefined) {
            this.adjustParticleCount(qualitySettings.particleCount);
        }
        
        // 调整阴影质量
        if (this.directionalLight.shadow) {
            const shadowMapSize = qualitySettings.shadowMapSize || 1024;
            this.directionalLight.shadow.mapSize.setScalar(shadowMapSize);
        }
        
        console.log(`${this.name} 质量调整完成`);
    }
    
    adjustParticleCount(factor) {
        // 子类实现粒子数量调整
    }
    
    performFrustumCulling(frustum) {
        this.cullableObjects.forEach(obj => {
            if (obj.geometry && obj.geometry.boundingSphere) {
                obj.visible = frustum.intersectsSphere(obj.geometry.boundingSphere);
            }
        });
    }
    
    performDistanceCulling(cameraPosition, maxDistance) {
        const maxDistanceSq = maxDistance * maxDistance;
        
        this.cullableObjects.forEach(obj => {
            const distanceSq = obj.position.distanceToSquared(cameraPosition);
            obj.visible = distanceSq <= maxDistanceSq;
        });
    }
    
    performLODOptimization(cameraPosition) {
        this.lodObjects.forEach(lodObj => {
            const distance = lodObj.position.distanceTo(cameraPosition);
            
            // 根据距离选择LOD级别
            if (distance < 20) {
                lodObj.setLevel(0); // 高详细度
            } else if (distance < 50) {
                lodObj.setLevel(1); // 中等详细度
            } else {
                lodObj.setLevel(2); // 低详细度
            }
        });
    }
    
    onResize(width, height) {
        // 处理窗口大小变化
        // 子类可以重写此方法实现特定的响应逻辑
    }
    
    /**
     * 添加对象到场景（自动分帧加载）
     * @param {Object} object - 要添加的对象
     * @param {Object} options - 添加选项
     */
    addObject(object, options = {}) {
        console.log('addObject called:', {
            object: object,
            objectType: object?.constructor?.name,
            objectName: object?.name,
            hasChildren: object?.children?.length > 0,
            options: options
        });
        
        // 如果指定不使用分帧加载，直接添加
        if (options.useFrameLoader === false) {
            console.log('Direct add (useFrameLoader: false)');
            this.addObjectImmediate(object);
            if (options.onAdd) {
                options.onAdd(object);
            }
            return;
        }

        // 自动分析对象复杂度，决定是否需要分帧加载
        const complexity = this.analyzeObjectComplexity(object);
        console.log('Complexity analysis:', complexity);
        
        if (complexity.shouldUseFrameLoader) {
            console.log('Using frame loader for complex object');
            // 使用分帧加载
            this.frameLoader.addToQueue(object, {
                priority: options.priority || complexity.priority,
                delay: options.delay || complexity.delay,
                onAdd: (obj) => {
                    console.log('Frame loader onAdd callback');
                    this.addObjectImmediate(obj);
                    if (options.onAdd) {
                        options.onAdd(obj);
                    }
                },
                metadata: {
                    ...options.metadata,
                    complexity: complexity
                }
            });
        } else {
            console.log('Direct add for simple object');
            // 简单对象直接添加
            this.addObjectImmediate(object);
            if (options.onAdd) {
                options.onAdd(object);
            }
        }
    }
    
    /**
     * 分析对象复杂度，决定分帧加载策略
     * @param {Object} object - 要分析的对象
     * @returns {Object} 复杂度分析结果
     */
    analyzeObjectComplexity(object) {
        const result = {
            shouldUseFrameLoader: false,
            priority: 0,
            delay: 0,
            meshCount: 0,
            childCount: 0,
            type: 'simple'
        };

        // 如果是Group或复杂对象，需要分帧加载
        if (object instanceof THREE.Group || object.children?.length > 0) {
            result.shouldUseFrameLoader = true;
            result.type = 'complex';
            result.childCount = object.children?.length || 0;
            
            // 计算网格数量
            let meshCount = 0;
            object.traverse((child) => {
                if (child instanceof THREE.Mesh) {
                    meshCount++;
                }
            });
            result.meshCount = meshCount;
            
            // 根据复杂度设置优先级和延迟
            if (meshCount > 10) {
                result.priority = 100; // 高优先级
                result.delay = 0;
            } else if (meshCount > 5) {
                result.priority = 80;  // 中优先级
                result.delay = 50;
            } else {
                result.priority = 60;  // 低优先级
                result.delay = 100;
            }
        }
        // 如果是单个Mesh且面数较多，也需要分帧加载
        else if (object instanceof THREE.Mesh && object.geometry) {
            const triangleCount = object.geometry.attributes?.position?.count / 3 || 0;
            if (triangleCount > 1000) {
                result.shouldUseFrameLoader = true;
                result.type = 'heavy_mesh';
                result.meshCount = 1;
                result.priority = 70;
                result.delay = 20;
            }
        }
        // 如果是其他复杂对象（如Points、LineSegments等）
        else if (object instanceof THREE.Points || object instanceof THREE.LineSegments) {
            const vertexCount = object.geometry?.attributes?.position?.count || 0;
            if (vertexCount > 500) {
                result.shouldUseFrameLoader = true;
                result.type = 'heavy_geometry';
                result.priority = 50;
                result.delay = 30;
            }
        }

        return result;
    }
    
    /**
     * 立即添加对象到场景（内部方法）
     * @param {Object} object - 要添加的对象
     */
    addObjectImmediate(object) {
        this.objects.push(object);
        this.group.add(object);
        
        // 如果对象支持剔除，添加到剔除列表
        if (object.geometry && object.geometry.boundingSphere) {
            this.cullableObjects.push(object);
        }
        
        // 触发对象添加事件
        this.onObjectAdded(object);
    }
    
    removeObject(object) {
        const index = this.objects.indexOf(object);
        if (index > -1) {
            this.objects.splice(index, 1);
            this.group.remove(object);
            
            // 从剔除列表中移除
            const cullIndex = this.cullableObjects.indexOf(object);
            if (cullIndex > -1) {
                this.cullableObjects.splice(cullIndex, 1);
            }
        }
    }
    
    // 遍历场景中所有mesh的方法
    getAllMeshes() {
        const meshes = [];
        
        // 方法1: 遍历this.objects数组中的mesh
        this.objects.forEach(obj => {
            if (obj instanceof THREE.Mesh) {
                meshes.push(obj);
            } else if (obj instanceof THREE.Group) {
                // 如果是Group，递归遍历其子对象
                obj.traverse(child => {
                    if (child instanceof THREE.Mesh) {
                        meshes.push(child);
                    }
                });
            }
        });
        
        return meshes;
    }
    
    // 遍历整个场景组的所有mesh
    getAllMeshesInGroup() {
        const meshes = [];
        
        // 使用Three.js的traverse方法遍历整个场景组
        this.group.traverse(child => {
            if (child instanceof THREE.Mesh) {
                meshes.push(child);
            }
        });
        
        return meshes;
    }
    
    // 按类型分类遍历对象
    getObjectsByType() {
        const result = {
            meshes: [],
            lights: [],
            points: [],
            lines: [],
            groups: [],
            others: []
        };
        
        this.group.traverse(child => {
            if (child instanceof THREE.Mesh) {
                result.meshes.push(child);
            } else if (child instanceof THREE.Light) {
                result.lights.push(child);
            } else if (child instanceof THREE.Points) {
                result.points.push(child);
            } else if (child instanceof THREE.Line) {
                result.lines.push(child);
            } else if (child instanceof THREE.Group) {
                result.groups.push(child);
            } else {
                result.others.push(child);
            }
        });
        
        return result;
    }
    
    // 调试方法：打印所有mesh信息
    debugAllMeshes() {
        console.log(`=== ${this.name} 场景中的所有Mesh ===`);
        
        const meshes = this.getAllMeshesInGroup();
        
        meshes.forEach((mesh, index) => {
            console.log(`Mesh ${index + 1}:`, {
                name: mesh.name || '未命名',
                type: mesh.type,
                position: mesh.position,
                visible: mesh.visible,
                material: mesh.material?.type || '无材质',
                geometry: mesh.geometry?.type || '无几何体',
                triangles: mesh.geometry?.attributes?.position?.count / 3 || 0
            });
        });
        
        console.log(`总共找到 ${meshes.length} 个Mesh`);
        return meshes;
    }
    
    // 操作所有mesh的方法
    setAllMeshesVisible(visible) {
        const meshes = this.getAllMeshesInGroup();
        meshes.forEach(mesh => {
            mesh.visible = visible;
        });
        console.log(`设置 ${meshes.length} 个mesh的可见性为: ${visible}`);
    }
    
    // 为所有mesh设置材质属性
    setAllMeshesMaterial(properties) {
        const meshes = this.getAllMeshesInGroup();
        meshes.forEach(mesh => {
            if (mesh.material) {
                Object.assign(mesh.material, properties);
            }
        });
        console.log(`为 ${meshes.length} 个mesh设置材质属性:`, properties);
    }
    
    /**
     * 分帧加载进度回调
     * @param {number} progress - 加载进度 (0-1)
     * @param {number} loaded - 已加载数量
     * @param {number} total - 总数量
     */
    onFrameLoadProgress(progress, loaded, total) {
        console.log(`${this.name} 分帧加载进度: ${(progress * 100).toFixed(1)}% (${loaded}/${total})`);
        
        // 可以在这里触发UI更新或其他进度显示
        if (this.app && this.app.onFrameLoadProgress) {
            this.app.onFrameLoadProgress(progress, loaded, total);
        }
    }
    
    /**
     * 分帧加载完成回调
     * @param {number} loaded - 已加载数量
     * @param {number} totalTime - 总耗时
     */
    onFrameLoadComplete(loaded, totalTime) {
        console.log(`${this.name} 分帧加载完成，共加载 ${loaded} 个对象，耗时 ${totalTime.toFixed(2)}ms`);
        
        // 可以在这里触发完成事件
        if (this.app && this.app.onFrameLoadComplete) {
            this.app.onFrameLoadComplete(loaded, totalTime);
        }
    }
    
    /**
     * 对象添加事件回调
     * @param {Object} object - 添加的对象
     */
    onObjectAdded(object) {
        // 子类可以重写此方法处理对象添加事件
        console.log(`${this.name} 添加对象:`, object.name || object.type || '未命名对象');
    }
    
    /**
     * 设置分帧加载配置
     * @param {Object} config - 配置对象
     */
    setFrameLoaderConfig(config) {
        if (this.frameLoader) {
            this.frameLoader.setConfig(config);
        }
    }
    
    /**
     * 获取分帧加载状态
     */
    getFrameLoaderStatus() {
        return this.frameLoader ? this.frameLoader.getStatus() : null;
    }
    
    /**
     * 暂停分帧加载
     */
    pauseFrameLoading() {
        if (this.frameLoader) {
            this.frameLoader.pause();
        }
    }
    
    /**
     * 恢复分帧加载
     */
    resumeFrameLoading() {
        if (this.frameLoader) {
            this.frameLoader.resume();
        }
    }
    
    dispose() {
        // 清理分帧加载器
        if (this.frameLoader) {
            this.frameLoader.clear();
        }
        
        // 清理资源
        this.objects.forEach(obj => {
            if (obj.geometry) obj.geometry.dispose();
            if (obj.material) {
                if (Array.isArray(obj.material)) {
                    obj.material.forEach(mat => mat.dispose());
                } else {
                    obj.material.dispose();
                }
            }
        });
        
        this.animations = [];
        this.objects = [];
        this.cullableObjects = [];
        this.lodObjects = [];
        
        console.log(`${this.name} 资源已清理`);
    }
}
